﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using ZLCMS.Business.Util;
using Newtonsoft.Json.Converters;
using DotNet.Common.Command;
using NHibernate;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Data.Model;
using System.Reflection;
using StackExchange.Redis;

namespace ZLCMS.Web.Interface.ajax
{
    public partial class CommandService : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            IsoDateTimeConverter convert = new IsoDateTimeConverter();
            convert.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

            object result = new CommandResult<object>() { ErrorCode = "0001", Result = "请根据规定调用接口" };

            string resultStr = "";
            string key = Request["key"];
            string param = Request["param"];
            string rediskey = key + param;

            if (!string.IsNullOrEmpty(key) && CommandFactory.Instance.CommandDictionary.ContainsKey(key))
            {


                CommandInfo cmdInfo = CommandFactory.Instance.CommandDictionary[key];
                if (ParamKit.GetValue("SystemConfig", "REDIS_VALID", "") == "1" && cmdInfo.CachedTime > 0 && RedisUtil.Conn.IsConnected)
                {
                    var db = RedisUtil.Conn.GetDatabase();

                    string dbresult = db.StringGet(rediskey);
                    if (dbresult == null)
                    {
                        resultStr = ExecuteCommand(convert, result, cmdInfo, key, param);
                        db.Wait(db.StringSetAsync(rediskey, resultStr, TimeSpan.FromSeconds(cmdInfo.CachedTime)));
                    }
                    else 
                    {
                        resultStr = dbresult;
                    }
                }
                else
                {
                    resultStr = ExecuteCommand(convert, result, cmdInfo, key, param);
                }
            }
            else
            {
                resultStr = JsonConvert.SerializeObject(result, convert);
            }
            if (resultStr.IndexOf("\"ErrorCode\":\"0000\"") ==-1)
            {
                CMSKits.WriteLog("commandservice", param, resultStr);
            }

            Response.Write(resultStr);
        }
        protected string ExecuteCommand(IsoDateTimeConverter convert, object result, CommandInfo cmdInfo, string key, string param)
        {
            CommandParameter paramObj = CommandFactory.Instance.DeserializeParameter(key, param);
            PropertyInfo memberAccountProp = paramObj.GetType().GetProperty("MemberAccount");
            PropertyInfo userAccountProp = paramObj.GetType().GetProperty("UserAccount");

            //权限不足
            if (cmdInfo.CommandLevel == CommandLevel.SYS || cmdInfo.CommandLevel == CommandLevel.APP)
            {
                result = new CommandResult<object>() { ErrorCode = "0007" };
            }
            //用户级别
            else if (userAccountProp != null && cmdInfo.CommandLevel == CommandLevel.USER)
            {
                string acc = UserKit.GetUserAccountWithoutException();
                if (string.IsNullOrEmpty(acc))
                {
                    result = new CommandResult<object>() { ErrorCode = "0109" };
                }
                else
                {
                    userAccountProp.SetValue(paramObj, acc, null);
                    result = new CommandExecutor().Execute(key, paramObj);
                }
            }
            //会员级别
            else if (memberAccountProp != null && cmdInfo.CommandLevel == CommandLevel.MEMBER)
            {
                string acc = Session[GlobalSessionString.CurrentMemberAccount] as string;

                //通过参数这设置帐号
                if(string.IsNullOrEmpty(acc))
                {
                    acc = Request["token"];
                }
                if (string.IsNullOrEmpty(acc))
                {
                    result = new CommandResult<object>() { ErrorCode = "0109" };
                }
                else
                {
                    memberAccountProp.SetValue(paramObj, acc, null);
                    result = new CommandExecutor().Execute(key, paramObj);
                }
            }
            else
            {
                result = new CommandExecutor().Execute(key, paramObj);
            }
            return JsonConvert.SerializeObject(result, convert);
        }
    }
}
